package com.zhao.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhao.Util.AgeUtil;
import com.zhao.Util.IPUtil;
import com.zhao.Util.NativePlace;
import com.zhao.pojo.*;
import com.zhao.service.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("/chart")
public class ChartController {

    //文章
    @Autowired
    private ArticleService articleService;
    //点赞 收藏
    @Autowired
    private ChartService chartService;
    //评论
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private FollowService followService;
    @Autowired
    OrdersService ordersService;
    @Autowired
    TransactionService transactionService;
    /**
     * 文章数据页面
     * @param model
     * @return
     */
    @RequestMapping("/articleChart")
    public String articleChart(Model model){

        //获取当前用户的 文章总数、粉丝数 点赞数、评论数、浏览量、积分、排名、收藏
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
       /* //文章总数
        List<Article> articles = articleService.list(new QueryWrapper<Article>().eq("author", loginUser.getUserAccount()));*/
        //总排名
        String rank= articleService.listTop(loginUser.getUserAccount());
        if ("".equals(rank)||rank==null){
            rank="无作品";
        }else if (Integer.parseInt(rank)>100){
            rank="未上榜";
        }
        //id的钱包
        Wallet wallet = walletService.getOne(new QueryWrapper<Wallet>().eq("uid", loginUser.getUserId()));
        //总评论 赞 浏览量
        Statistic statistic =userService.SumStatistic(loginUser.getUserAccount());
        if (statistic==null){
            statistic =new Statistic();
            statistic.setHits(0);
            statistic.setCommentsNum(0);
            statistic.setZan(0);
        }else {
            if (Objects.isNull(statistic.getHits())) {
                statistic.setHits(0);
            }
            if (Objects.isNull(statistic.getCommentsNum())){
                statistic.setCommentsNum(0);
            }
            if (Objects.isNull(statistic.getZan())){
                statistic.setZan(0);
            }
        }
        //获取收藏数
        int chartSize = chartService.list(new QueryWrapper<Chart>().eq("bauthor", loginUser.getUserAccount()).eq("type", 1)).size();
        //获取关注数
        int fidSize = followService.list(new QueryWrapper<Follow>().eq("fid", loginUser.getUserId())).size();
        model.addAttribute("rank",rank);
        model.addAttribute("statistic",statistic);
        model.addAttribute("wallet",wallet);
        model.addAttribute("chartSize",chartSize);
        model.addAttribute("fidSize",fidSize);
        return "admin/articleChart";
    }

    /**
     * 收益数据页面
     * @param model
     * @return
     */
    @RequestMapping("/yieldChart")
    public String yieIdChart(Model model){
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        List<String> list = IPUtil.before7Day(30, 1);
        //获取昨日收入
        String before1DPrice=ordersService.queryDayBetweenDaySumPrice(loginUser.getUserId(),list.get(list.size()-2)+" 00:00:00",list.get(list.size()-2)+" 23:59:59");
        if (before1DPrice==null){
            before1DPrice="0";
        }
        //本月
        String month = IPUtil.month();
        String s = list.get(list.size() - 1);
        String before1MPrice=ordersService.queryDayBetweenDaySumPrice(loginUser.getUserId(),IPUtil.month()+" 00:00:00",list.get(list.size()-1)+" 23:59:59");
        if (before1MPrice==null){
            before1MPrice="0";
        }
        //近三十天
        String before30DPrice=ordersService.queryDayBetweenDaySumPrice(loginUser.getUserId(),list.get(0)+" 00:00:00",list.get(29)+" 23:59:59");
        if (before30DPrice==null){
            before30DPrice="0";
        }
        //全部
        //可提现 未实现
        Wallet wallet = walletService.getOne(new QueryWrapper<Wallet>().eq("uid", loginUser.getUserId()));
        List<String> arrayList=new ArrayList<>();
        arrayList.add(before1DPrice);
        arrayList.add(before1MPrice);
        arrayList.add(before30DPrice);
        arrayList.add(wallet.getGolds());//全部金币
        arrayList.add(String.format("%.2f", Integer.parseInt(wallet.getGolds()) * 0.1));//可提现String.format("%.2f", 3.14563)Integer.parseInt(wallet.getGolds()) * 0.09
        model.addAttribute("arrayList",arrayList);
        return "admin/yieldChart";
    }
    @RequestMapping("/userChart")
    public String userChart(){
        return "admin/userChart";
    }
    /**
     * 7天内文章数据
     * @return
     */
    @ResponseBody
    @RequestMapping("/chartList")
    public String chartList(){
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        //获取用户的全部文章的评论 id
        List<Integer> cIds=commentService.queryAuthorByIds(loginUser.getUserAccount());
        List<String> before7Day = IPUtil.before7Day(7,1);

        int []hitNum=new int[7];
        int []commentNum=new int[7];
        int []followNum=new int[7];
        int []collectNum=new int[7];
        int i=0;
        for (String s:before7Day) {
            hitNum[i]=chartService.list(new QueryWrapper<Chart>().eq("bauthor",loginUser.getUserAccount()).eq("type",0).between("create_time",s+" 00:00:00",s+" 23:59:59")).size();
            if (cIds.isEmpty()){
                commentNum[i] = 0;
            }else {
                commentNum[i] =commentService.list(new QueryWrapper<Comment>().in("article_id", cIds).between("create_time",s+" 00:00:00",s+" 23:59:59")).size();
            }
            followNum[i]=followService.list(new QueryWrapper<Follow>().eq("fid",loginUser.getUserId()).between("create_time",s+" 00:00:00",s+" 23:59:59")).size();
            collectNum[i]=chartService.list(new QueryWrapper<Chart>().eq("bauthor",loginUser.getUserAccount()).eq("type",1).between("create_time",s+" 00:00:00",s+" 23:59:59")).size();
            i++;
        }
        String[] day = before7Day.toArray(new String[]{});
        Map<String,Object> msg=new HashMap<>();
        msg.put("day",day);
        msg.put("hitNum",hitNum);
        msg.put("commentNum",commentNum);
        msg.put("followNum",followNum);
        msg.put("collectNum",collectNum);

        return JSONObject.toJSONString(msg);
    }

    /**
     * 7天内收益数据
     * @return
     */
    @ResponseBody
    @RequestMapping("/yieldList")
    public String yieldList(){
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        List<String> before7Day = IPUtil.before7Day(7,1);

        int []priceNum=new int[7];
        int []xiaNum=new int[7];
        int i=0;
        for (String s:before7Day) {
            String price=ordersService.queryDayBetweenDaySumPrice(loginUser.getUserId(),before7Day.get(i)+" 00:00:00",before7Day.get(i)+" 23:59:59");
            if (price==null){
                price="0";
            }
            priceNum[i]=Integer.parseInt(price);
            xiaNum[i]=transactionService.list(new QueryWrapper<Transaction>().eq("seller",loginUser.getUserId()).between("create_time",s+" 00:00:00",s+" 23:59:59")).size();
            i++;
        }

        String[] day = before7Day.toArray(new String[]{});
        Map<String,Object> msg=new HashMap<>();
        msg.put("day",day);
        msg.put("priceNum",priceNum);
        msg.put("xiaNum",xiaNum);
        return JSONObject.toJSONString(msg);
    }
    @ResponseBody
    @RequestMapping("/userList")
    public String userList() throws ParseException {

        Map<String,Object> map=new HashMap<>();
        map.put("max",walletService.list(null).size());
        List<Map<String,Object>> chinaList=new ArrayList<>();
        List<Map<String,Object>> sexList=new ArrayList<>();
        List<Map<String,Object>> ageList=new ArrayList<>();
        List<Map<String,Object>> gradeList=new ArrayList<>();
        Map<String,Object> dataMap=null;
        //China数据
        //初始化所有省份
        for (int i = 10; i <100 ; i++) {
            String nativePlace = NativePlace.getShengName(i,true);
            if (!nativePlace.equals("")){
                dataMap=new HashMap<>();
                dataMap.put("name",nativePlace);
                dataMap.put("value",walletService.list(new QueryWrapper<Wallet>().select("area").likeRight("area", i)).size()+"");
                chinaList.add(dataMap);
            }
        }
        //男女数据
        List<Wallet> sex = walletService.list(new QueryWrapper<Wallet>().select("sex,count(*) AS area").groupBy("sex"));
        for (Wallet wallet:sex) {
            dataMap=new HashMap<>();
            if (wallet.getSex()==null){
                dataMap.put("name","未知");
            }else {
                dataMap.put("name",wallet.getSex());
            }
            dataMap.put("value",wallet.getArea());//临时存储数量
            sexList.add(dataMap);
        }
        //年龄数据
        ageList= AgeUtil.getAnalyzeAge(walletService.getAge());
        //等级数据
        List<Wallet> grade = walletService.list(new QueryWrapper<Wallet>().select("grade,count(*) AS area").groupBy("grade"));
        for (Wallet wallet:grade) {
            dataMap=new HashMap<>();
            dataMap.put("name",wallet.getGrade());
            dataMap.put("value",wallet.getArea());//临时存储数量
            gradeList.add(dataMap);
        }
        //用户增长 活跃
        //获取时间
        List<String> before7Day = IPUtil.dayToDay("2020-01-01");
        String[] day = before7Day.toArray(new String[]{});
        //定义用户注册数量 存储变量
        int[] usersNum=new int[before7Day.size()];
        //查询 某一天之前注册的全部用户
        int i=0;
        for (String s:before7Day) {
            usersNum[i]=userService.list(new QueryWrapper<User>().between("create_time","2020-01-01 00:00:00",s+" 23:59:59")).size();
            i++;
        }
        map.put("chinaList",chinaList);
        map.put("sexList",sexList);
        map.put("ageList",ageList);
        map.put("gradeList",gradeList);
        map.put("day",day);
        map.put("usersNum",usersNum);
        return JSONObject.toJSONString(map);
    }
}
